package com.dries.portal.module.coupon.vo;

import com.dries.portal.module.coupon.enums.CouponStatus;
import com.dries.portal.module.coupon.enums.PeriodType;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.time.DateUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @Description: 用户优惠券的分类
 * @Author ZSY
 * @createTime 2020/7/30 9:51
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class CouponClassify {

    /**
     * 未使用的优惠券
     */
    private List<CouponVo> usable;
    /**
     * 已使用的优惠券
     */
    private List<CouponVo> used;
    /**
     * 已过期的优惠券
     */
    private List<CouponVo> expired;

    /**
     * 对当前的优惠券进行分类
     */
    public static CouponClassify classify(List<CouponVo> coupons) {
        List<CouponVo> usable = new ArrayList<>();
        List<CouponVo> used = new ArrayList<>();
        List<CouponVo> expired = new ArrayList<>();

        coupons.forEach(e -> {
            // 判断优惠券是否过期
            boolean isTimeExpired;
            long curTime = System.currentTimeMillis();
            if (e.getTemplateSDK().getRule().getExpiration().getPeriod().equals(PeriodType.REGULAR.getCode())){
                isTimeExpired = (e.getTemplateSDK().getRule().getExpiration().getDeadline().compareTo(new Date()) < 0);
            } else {
                isTimeExpired = DateUtils.addDays(e.getAssignTime(),
                        e.getTemplateSDK().getRule().getExpiration().getGap())
                        .getTime() <= curTime;
            }

            if (Objects.equals(e.getStatus(), CouponStatus.USED.getCode())) {
                used.add(e);
            } else if (Objects.equals(e.getStatus(), CouponStatus.EXPIRED.getCode()) || isTimeExpired) {
                expired.add(e);
            } else {
                usable.add(e);
            }
        });

        return new CouponClassify(usable, used, expired);
    }

}
